﻿using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using Framework.Entities.mysql;
using MySql.Data.MySqlClient;
using ServiceStack.Text;

namespace SignalPositionProcesser.DataAccess
{
    public static class RawdataDA
    {
        private static String ConnectionString => "Server=127.0.0.1;User ID=root;Password=mxky@123;Database=chinamobile";

        /// <summary>
        /// channelIds contains Id2 column
        /// </summary>
        /// <param name="channelIds"></param>
        /// <returns></returns>
        public static List<RawChannel> GetRawChannelList(List<string> channelIds)
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                var sql = "SELECT Id AS ChannelUid, Id2 AS ChannelId, `Name` AS ChannelName FROM `channel` ";
                if (!channelIds.IsNullOrEmpty())
                {
                    sql += $"WHERE Id2 IN ({string.Join(",", channelIds)})";
                }
                var result = conn.Query<RawChannel>(sql).ToList();

                return result;
            }
        }

        /// <summary>
        /// deviceIdList contains ChannelId column
        /// </summary>
        /// <param name="channelIdList"></param>
        /// <returns></returns>
        public static List<RawDevice> GetRawDeviceList(List<string> channelIdList)
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                var sql = "SELECT Id AS DeviceUid, Id2 AS DeviceId, `Name` AS DeviceName, ChannelId AS ChannelId FROM `device` ";
                if (!channelIdList.IsNullOrEmpty())
                {
                    sql += $"WHERE ChannelId IN ({string.Join(",", channelIdList.Select(x => $"'{x.ToString()}'").ToArray())})";
                }
                var result = conn.Query<RawDevice>(sql).ToList();

                return result;
            }
        }

        public static List<RawSignal> GetRawSignalList(List<string> deviceIdList)
        {
            using (var conn = new MySqlConnection(ConnectionString))
            {
                var sql = "SELECT Id AS SignalUid, Id2 AS SignalId, `Name` AS SignalName, DeviceId AS DeviceId, Unit FROM `signal` ";
                if (!deviceIdList.IsNullOrEmpty())
                {
                    sql += $"WHERE DeviceId IN ({string.Join(",", deviceIdList.Select(x => $"'{x.ToString()}'").ToArray())})";
                }
                var result = conn.Query<RawSignal>(sql).ToList();

                return result;
            }
        }

    }
}
